package com.xinchuang.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinchuang.entity.api.UserApi;
import com.xinchuang.mapper.UserApiMapper;
import com.xinchuang.role.entity.SystemHeader;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/7/5 11:49
 */
public class MyUtils {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static DecimalFormat decimalFormat = new DecimalFormat("#0.00");

    /**
     * 创建SimpleDateFormat对象，指定日期格式为ISO 8601
     */
    private static SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");

    public static String getLocalDataTimeByString(String time) {
//        if (ObjectUtil.isNotEmpty(time)) {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            return time.format(formatter);
//        }
        return time;
    }

    public static String getLocalDataTimeBetweenTime(String startTime, String endTime) {
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            double value = duration.toMinutes() / 60.0;
            String format = decimalFormat.format(value);
            if (format.equals("0.00")) {
                return "0";
            }
            return format;
        }
        return "";
    }

    public static Long getTimeByLong(String startTime, String endTime) {
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            return duration.toMillis();
        }
        return 0L;
    }

    public static String getTime(long time) {
        if (time == 0L) {
            return "0";
        }
//        else if (time < 60 * 1000) {
//            return (time / 1000) + "秒";
//        } else if (time >= 60 * 1000 && time <= 60 * 60 * 1000) {
//            return formatDouble(time / 1000 / 60.0) + "分钟";
//        }
        else {
            return formatDouble(time / 1000 / 60.0 / 60.0) + "小时";
        }
    }

    public static String getTimeNo(long time) {
        if (time == 0L) {
            return "0";
        } else {
            return formatDouble(time / 1000 / 60.0 / 60.0);
        }
    }

    public static String getMoney(long time, Double price) {
        if (time == 0L) {
            return "0";
        } else if (time <= 60 * 60 * 1000) {
            return formatDouble(price);
        } else {
            return formatDouble(time / 1000 / 60.0 / 60.0 * price);
        }
    }

    public static double getMoneyDouble(long time, Double price) {
        if (time == 0L) {
            return 0;
        } else if (time <= 60 * 60 * 1000) {
            return price;
        } else {
            return time / 1000 / 60.0 / 60.0 * price;
        }
    }

    public static double getLocalDataTimeBetweenTimeByLong(String startTime, String endTime) {
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            return duration.toMinutes() / 60;
        }
        return 0.0;
    }

    public static double getLocalDataTimeByDouble(String startTime, String endTime) {
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            Duration duration = Duration.between(start, end);
            return duration.toMinutes() / 60.0;
        }
        return 0.0;
    }

    public static String formatDouble(double value) {
        String format = decimalFormat.format(value);
        if ("0.0000".equals(format)) {
            return "0";
        }
        return format;
    }

    public static double formatToDouble(double value) {
        BigDecimal bigDecimal = new BigDecimal(value);
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static JSONArray getJSONArray(String str) {
        if (StringUtils.isNotBlank(str)) {
            return JSONArray.parseArray(str);
        }
        return new JSONArray();
    }

    public static String getMonthStartDay(String year, int month) {
        if (StringUtils.isBlank(year)) {
            year = DateUtil.year(new Date()) + "";
        }
        String time = year + "-" + (month < 10 ? "0" : "") + month + "-01 00:00:00";
        LocalDateTime currentDate = LocalDateTime.parse(time, formatter);
        LocalDateTime lastDayOfMonth = currentDate.with(TemporalAdjusters.firstDayOfMonth());
        return lastDayOfMonth.getYear() + "-" + (lastDayOfMonth.getMonthValue() < 10 ? "0" : "") + lastDayOfMonth.getMonthValue() + "-" + (lastDayOfMonth.getDayOfMonth() < 10 ? "0" : "") + lastDayOfMonth.getDayOfMonth() + " 00:00:00";
    }

    public static String getMonthEndDay(String year, int month) {
        if (StringUtils.isBlank(year)) {
            year = DateUtil.year(new Date()) + "";
        }
        String time = year + "-" + (month < 10 ? "0" : "") + month + "-01 00:00:00";
        LocalDateTime currentDate = LocalDateTime.parse(time, formatter);
        LocalDateTime lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDayOfMonth.getYear() + "-" + (lastDayOfMonth.getMonthValue() < 10 ? "0" : "") + lastDayOfMonth.getMonthValue() + "-" + lastDayOfMonth.getDayOfMonth() + " 23:59:59";
    }

    public static JSONObject getMonthTimeAll(int month, List<Map<String, Long>> list) {
        JSONObject data = new JSONObject();
        //月份
        data.put("month", month + "月");
        //总时间
        data.put("totalTime", 0);
        //等待时间
        data.put("waitTime", 0);
        //设备故障时间
        data.put("breakdownTime", 0);
        //修模时间
        data.put("fixTime", 0);
        if (CollectionUtil.isNotEmpty(list)) {
            long totle = 0;
            long wait = 0;
            long breakdown = 0;
            long fix = 0;
            for (Map<String, Long> map : list) {
                Long status = map.get("status");
                if (status == 2) {
                    wait += map.get("intervals");
                } else if (status == 5) {
                    breakdown += map.get("intervals");
                } else if (status == 6) {
                    fix += map.get("intervals");
                }
                totle += map.get("intervals");
            }
            data.put("totalTime", getTimeNo(totle));
            data.put("waitTime", getTimeNo(wait));
            data.put("breakdownTime", getTimeNo(breakdown));
            data.put("fixTime", getTimeNo(fix));
        }
        return data;
    }

    public static int getWeeksInYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.WEEK_OF_YEAR, 1);
        int weeksInYear = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
        return weeksInYear;
    }

    public static String getYearWeekDays(int year, int weeek, int type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.YEAR, year);

        calendar.set(Calendar.WEEK_OF_YEAR, weeek);

        calendar.set(Calendar.DAY_OF_WEEK, 2);

        if (type == 2) {
            Date startDate = calendar.getTime();

            calendar.setTime(startDate);

            calendar.add(Calendar.DATE, 6);

            Date endDate = calendar.getTime();

            return format.format(endDate) + " 23:59:59";
        }

        Date startDate = calendar.getTime();

        return format.format(startDate) + " 00:00:00";
    }

    public static String getWeekStartDays(int weeek) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.YEAR, DateUtil.year(new Date()));

        calendar.set(Calendar.WEEK_OF_YEAR, weeek);

        calendar.set(Calendar.DAY_OF_WEEK, 2);

        Date startDate = calendar.getTime();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        return format.format(startDate) + " 00:00:00";
    }

    public static Date getWeekToDate(int year, int weeek, int type) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.YEAR, year);

        calendar.set(Calendar.WEEK_OF_YEAR, weeek);

        calendar.set(Calendar.DAY_OF_WEEK, 2);

        if (type == 2) {
            Date startDate = calendar.getTime();

            calendar.setTime(startDate);

            calendar.add(Calendar.DATE, 6);

            Date endDate = calendar.getTime();

            return endDate;
        }

        return calendar.getTime();
    }

    public static Integer getWeekNum(Date time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

    public static String getWeekEndDays(int weeek) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.YEAR, DateUtil.year(new Date()));

        calendar.set(Calendar.WEEK_OF_YEAR, weeek);

        calendar.set(Calendar.DAY_OF_WEEK, 2);

        Date startDate = calendar.getTime();

        calendar.setTime(startDate);

        calendar.add(Calendar.DATE, 6);

        Date endDate = calendar.getTime();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        return format.format(endDate) + " 23:59:59";
    }

    public static int getWeekNumber() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 初始化射胶参数对象数组
     *
     * @return
     */
    public static JSONArray ejectionEjectionParams() {
        JSONArray resultList = new JSONArray();
        JSONObject map;
        String ejectionStageName;
        for (int i = 0; i < 5; i++) {
            switch (i) {
                case 0:
                    ejectionStageName = "第一段";
                    break;
                case 1:
                    ejectionStageName = "第二段";
                    break;
                case 2:
                    ejectionStageName = "第三段";
                    break;
                case 3:
                    ejectionStageName = "第四段";
                    break;
                case 4:
                    ejectionStageName = "第五段";
                    break;
                default:
                    ejectionStageName = "";
            }
            map = new JSONObject();
            map.put("ejectionStageName", ejectionStageName);
            map.put("ejectionTempresure", "");
            map.put("ejectionSpeed", "");
            map.put("ejectionposition", "");
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 初始化螺杆温度参数对象数组
     *
     * @return
     */
    public static JSONArray screwTemperature() {
        JSONArray resultList = new JSONArray();
        ;
        JSONObject map;
        String stageName;
        for (int i = 0; i < 5; i++) {
            switch (i) {
                case 0:
                    stageName = "第一段";
                    break;
                case 1:
                    stageName = "第二段";
                    break;
                case 2:
                    stageName = "第三段";
                    break;
                case 3:
                    stageName = "第四段";
                    break;
                case 4:
                    stageName = "第五段";
                    break;
                default:
                    stageName = "";
            }
            map = new JSONObject();
            map.put("stageName", stageName);
            map.put("temperatureValue", "");
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 初始化顺序阀进胶方式参数对象数组
     *
     * @return
     */
    public static JSONArray sequentialValveFeedingMode() {
        JSONArray resultList = new JSONArray();
        JSONObject map;
        for (int i = 1; i <= 20; i++) {
            map = new JSONObject();
            map.put("number", i);
            map.put("start", "");
            map.put("end", "");
            map.put("pressure", "");
           // map.put("gluingmethod", "");
            resultList.add(map);
        }
        return resultList;
    }

    public static int getInteger(String number) {
        int result = 0;
        try {
            if (StringUtils.isNotBlank(number)) {
                return Integer.parseInt(number);
            }
        } catch (Exception e) {
            return 0;
        }
        return result;
    }

    public static Boolean getBoolean(String number) {
        try {
            if (StringUtils.isNotBlank(number)) {
                if ("是".equals(number)) {
                    return true;
                } else if ("否".equals(number)) {
                    return false;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static String getString(String number) {
        String result = "";
        try {
            if (StringUtils.isNotBlank(number)) {
                return number;
            }
        } catch (Exception e) {
            return "";
        }
        return result;
    }

    public static String getStringToStr(String number) {
        String result = "无";
        try {
            if (StringUtils.isNotBlank(number)) {
                return number;
            }
        } catch (Exception e) {
            return "无";
        }
        return result;
    }

    public static String objGetString(Object obj) {
        String result = "";
        try {
            if (ObjectUtil.isNotEmpty(obj)) {
                return obj.toString();
            }
        } catch (Exception e) {
            return "";
        }
        return result;
    }

    public static String getObjectString(Object value) {
        try {
            if (ObjectUtil.isNotEmpty(value)) {
                return value.toString();
            }
        } catch (Exception e) {
            return "";
        }
        return "";
    }

    public static Double getDouble(Double number) {
        Double result = 0.0;
        try {
            if (ObjectUtil.isNotEmpty(number)) {
                return number;
            }
        } catch (Exception e) {
            return 0.0;
        }
        return result;
    }

    public static Double getDoubleByString(String number) {
        Double result = 0.0;
        try {
            if (StringUtils.isNotBlank(number)) {
                return Double.valueOf(number);
            }
        } catch (Exception e) {
            return 0.0;
        }
        return result;
    }

    public static Double formatDouble(String value) {
        try {
            return Double.valueOf(value.trim());
        } catch (Exception e) {
            return 0D;
        }
    }

    public static Date stringToDate(String time) {
        try {
            return DateUtil.parse(time, "yyyy-MM-dd");
        } catch (Exception e) {

        }
        try {
            return DateUtil.parse(time, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 字符串转换List
     *
     * @param stringList
     * @return
     */
    public static List getStringTransitionList(String stringList) {
        if (StringUtils.isBlank(stringList)) {
            return new ArrayList();
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(stringList, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList();
        }
    }

    public static String[] getMothStartAndEnd() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDayOfMonth = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.DATE, -1);
        String[] strings = {DateUtil.format(firstDayOfMonth, "yyyy-MM-dd") + " 00:00:00",
                DateUtil.format(firstDayOfMonth, "yyyy-MM-dd") + " 23:59:59"};
        return strings;
    }

    public static SystemHeader getHeader(HttpServletRequest request) {
        String id = request.getHeader("id");
        String name = request.getHeader("name");
        String userName = request.getHeader("userName");
        try {
            userName = URLDecoder.decode(userName, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String operations = request.getHeader("operations");
        String routes = request.getHeader("routes");
        String token = request.getHeader("token");
        SystemHeader systemHeader = new SystemHeader();
        systemHeader.setId(id);
        if (StringUtils.isNotBlank(operations)) {
            String[] split = operations.split(",");
            systemHeader.setOperations(Arrays.asList(split));
        }
        if (StringUtils.isNotBlank(routes)) {
            String[] split1 = routes.split(",");
            systemHeader.setRoutes(Arrays.asList(split1));
        }
        systemHeader.setToken(token);
        systemHeader.setUserName(userName);
        return systemHeader;
    }

    public static String getName(String userId) {
        UserApiMapper userApiMapper = SpringUtil.getBean(UserApiMapper.class);
        UserApi userApi = userApiMapper.selectById(userId);
        return userApi.getName();
//        if (id.equals("123456789")) {
//            return "部长";
//        } else if (id.equals("987654321")) {
//            return "项目经理";
//        } else if (id.equals("147258369")) {
//            return "试模工";
//        } else if (id.equals("963852741")) {
//            return "唐东海";
//        }
//        return "王涵";
    }

    public static int getNum(String one, String two) {
        try {
            int value1 = Integer.parseInt(one);
            int value2 = Integer.parseInt(two);
            if (value1 < value2) {
                return 0;
            } else {
                return value1 - value2;
            }
        } catch (Exception e) {

        }
        return 0;
    }

    public static String getSubTarget(String a, String b, String status) {
        try {
            if (b.contains(status)) {
                if (StringUtils.isNotBlank(a)) {
                    Integer z = Integer.valueOf(a.split(status)[1]);
                    Integer z1 = Integer.valueOf(b.split(status)[1]);
                    if (z1 > z) {
                        return b;
                    }
                } else {
                    return b;
                }
            }
        } catch (Exception e) {

        }
        return a;
    }

    /**
     * @param type   1 审批验证
     * @param status
     * @return
     */
    public static boolean verifyNotice(int type, String status) {
        int parseInt = Integer.parseInt(status);
        if (type == 1) {
            if (parseInt < 1 || parseInt > 4) {
                if (parseInt != 8) {
                    return true;
                }
            }
        }
        return false;
    }

    public static UserApi createUserApi(String name, String username, Integer id) {
        JSONArray array = new JSONArray();
        array.add("string");
        UserApi userApi = new UserApi();
        userApi.setName(name);
        userApi.setUsername(username);
        userApi.setDepartment("string");
        userApi.setIsActive(true);
        userApi.setOperationList(array.toJSONString());
        userApi.setRoleList(array.toJSONString());
        userApi.setId(id);
        return userApi;
    }

    public static boolean isISO8601(String dateTimeString) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        try {
            formatter.parse(dateTimeString);
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }

    public static String dataToIso8601(Date date) {
        if (ObjectUtil.isNotEmpty(date)) {
            try {
                return iso8601.format(date);
            } catch (Exception e) {
                return "";
            }
        }
        return "";
    }

    public static int convertToInt(String input) {
        int intValue;
        if (input.contains(".")) {
            String[] parts = input.split("\\.");
            intValue = Integer.parseInt(parts[0]);
        } else {
            intValue = Integer.parseInt(input);
        }
        return intValue;
    }

}
